package org.webArchi.common.utill;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.webArchi.common.Permission;
import org.webArchi.common.api.dao.RoleDAO;
import org.webArchi.common.api.domain.Role;

import java.util.BitSet;

/**
 * util class for permission settings and related methods
 *
 * @authar amith jayasekara
 */
public class RolePermissionUtils {
    private static final Logger logger = LoggerFactory.getLogger(RolePermissionUtils.class);

    private static final BitSet guestBitSet;
    private static final BitSet normalUserBitSet;

    private static final BitSet coopUserBitSet;
    private static final BitSet adminUserBitSet;


    static {
        // Guest users
        guestBitSet = new BitSet();
        guestBitSet.set(Permission.EDIT_USER_INFO);
        guestBitSet.set(Permission.FULL_PERMISSION);


        //NORMAL
        normalUserBitSet = new BitSet();
        normalUserBitSet.or(guestBitSet);


        // COOP USER
        coopUserBitSet = new BitSet();
        coopUserBitSet.or(normalUserBitSet);


        // ADMIN
        adminUserBitSet = new BitSet();
        adminUserBitSet.set(Permission.EDIT_USER_INFO);
        adminUserBitSet.set(Permission.FULL_PERMISSION);


    }

    public static void setPermissionBits(ApplicationContext ctx) {
        try {
            // ---------------- populate permissions ---------------------
            RoleDAO roleDao = (RoleDAO) ctx.getBean("roleDAOImpl", RoleDAO.class);

            Role guestRole = roleDao.getRole("GUEST");
            guestRole.setPermBitSet(guestBitSet);
            roleDao.save(guestRole);

            Role normalRole = roleDao.getRole("NORMAL_USER");
            normalRole .setPermBitSet(normalUserBitSet);
            roleDao.save(normalRole );

            Role coUserRole = roleDao.getRole("CO_USER");
            coUserRole.setPermBitSet(coopUserBitSet);
            roleDao.save(coUserRole);

            Role adminRole = roleDao.getRole("ADMIN");
            adminRole.setPermBitSet(adminUserBitSet);
            roleDao.save(adminRole);

            logger.info("Initialized the database by performing permission initialization");

        } catch (Exception e) {
            logger.error("Error initializing role permissions on the database");
            throw new IllegalStateException("Error initializing role permissions. See log for details", e);
        }
    }
}
